import { useState, useEffect, useRef, useMemo } from 'react';
import { Button, Card, Col, Empty, Row, Switch, message } from 'antd';
import IconFont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import ChangePriceModal from './ChangePriceModal';
import AmountChangeRecord from './AmountChangeRecord';
import FormRender from '@/components/FormRender';
import { formatAmount } from '@/utils/utils.jsx';
import { deductionStoreListOp, autoDedication, queryAutoDedication } from '../service';
import { getFormItem } from './config.js';
import styles from './index.module.less';


export default ({ accountMsg, handleJump }) => {

  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState({});
  const [data, setData] = useState([]);

  const [itemData, setItemData] = useState({}); //当前点击的选项
  const [visible, setVisible] = useState(false); //调整价格的弹窗
  const [recordVisible, setRecordVisible] = useState(false);//金额调整记录的弹框
  const [isChecked, setIsChecked] = useState(false); //自动抵扣开关

  const totalDeductionBalance = useRef(0);
  const totalChangeTimes = useRef(0);

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem();
  }, [])

  useEffect(() => {
    getStoreListFunc();
  }, [query])

  useEffect(() => {
    getAutoDedication();
  }, [])

  const getStoreListFunc = async () => {
    setLoading(true);
    const { data, success } = await deductionStoreListOp({
      merchantNos: query?.merchantNos ? query.merchantNos.join(',') : undefined
    });
    setLoading(false);
    if (success && data) {
      const { storeList = [], totalDeductionBalance: newAmount, totalChangeTimes: newTotalChangeTimes } = data;
      totalDeductionBalance.current = newAmount;
      totalChangeTimes.current = newTotalChangeTimes || 0;
      setData(storeList);
    } else {
      totalDeductionBalance.current = 0;
      totalChangeTimes.current = 0;
      setData([]);
    }
  }

  //查询是否自动抵扣
  const getAutoDedication = async () => {
    setLoading(true);
    const { data, success } = await queryAutoDedication({
      accountNo: accountMsg.accountNo
    });
    if (success) {
      setIsChecked(data);
    }
    setLoading(false);
  };


  //点击调整价格
  const handleChangePrice = (e, item) => {
    e.stopPropagation();
    setVisible(true);
    setItemData(item);
  }

  //切换是否自动抵扣
  const handleSwitch = async (e) => {
    setLoading(true);
    const { success, msg } = await autoDedication({
      status: e ? 1 : 0,
      accountNo: accountMsg.accountNo
    });
    if (success) {
      message.success(msg);
      getAutoDedication();
    }
    setLoading(false);
  };


  //调整价格modal
  const ChangePriceModalProps = {
    visible,
    itemData,
    handleCancel() {
      setVisible(false);
      setItemData({});
    },
    handleOk() {
      getStoreListFunc();
      setVisible(false);
      setItemData({});
    }
  }

  //金额调整记录modal
  const AmountChangeRecordProps = {
    visible: recordVisible,
    handleCancel() {
      setRecordVisible(false);
    }
  }

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'refund-detail-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setQuery(val);
    },
    clickReset() {
      setQuery({});
    },
  }

  return (<>
    <div className={styles.amountSection}>
      <div className={styles.iconLeft}>
        <IconFont type="iconbalance" />
      </div>
      <div className={styles.amountBox} style={{ marginLeft: '16px' }}>
        可抵扣总金额：
        <span className='common-color9'>
          {formatAmount(Number(totalDeductionBalance?.current || 0))}
        </span>&nbsp;元
      </div>
      <Button style={{ fontSize: '14px', marginLeft: '32px' }} onClick={() => setRecordVisible(true)} className={styles.changePrice}>金额调整记录</Button>
      <div style={{ marginLeft: 'auto' }}>
        开启自动抵扣：
        <Switch checked={isChecked} onChange={handleSwitch} />
      </div>
    </div>
    <FormRender {...FormRenderProps} />
    {
      data.length ? (<div className={styles.siteCardWrapper}>
        <Row gutter={[16, 16]}>
          {
            data.map((item, index) => {
              const { storeName, deductionBalance = 0.00, merchantNo, purchaseDeductionBalance = 0.00, changeTimes = 0 } = item;
              return (<Col span={6} key={index} onClick={() => handleJump({ merchantNo, step: 3 })}>
                <Card style={{ cursor: 'pointer', textAlign: 'center', position: 'relative' }}>
                  <h3>{storeName}</h3>
                  <div style={{ marginBottom: '6px' }} className="common-color9">
                    <span className={styles.textIcon}>拿</span>
                    {formatAmount(deductionBalance)}
                  </div>
                  <div className="common-color9">
                    <span className={styles.textIcon}>采</span>
                    {formatAmount(purchaseDeductionBalance)}
                  </div>
                  <Button style={{ position: 'absolute', right: '12px', top: '12px' }} onClick={(e) => { handleChangePrice(e, item) }} className={styles.changePrice}>金额调整</Button>
                  <div>可抵扣金额（元）</div>
                </Card>
              </Col>)
            })
          }
        </Row>
      </div>) : <Empty style={{ marginTop: "120px" }} />
    }
    {visible && <ChangePriceModal {...ChangePriceModalProps} />}
    {recordVisible && <AmountChangeRecord {...AmountChangeRecordProps} />}
    <CommonLoading loading={loading} />
  </>)
}